<template>
	<div class="h-full bg-white">
		<PageWrapper fixedHeight>
			<div class="pl-30 pr-30">
				<BasicForm @register="register" />
			</div>
		</PageWrapper>
	</div>
</template>

<script setup lang="ts">
import { BasicForm, PageWrapper } from '#/components';
import { useForm } from '#/hooks';
import { useMessage } from '@/hooks/web/useMessage';
import { ref } from 'vue';
import { FormSchema } from '#/types';
import { downloadByUrl } from '@/utils/file/download';
import { uploadFile } from '@/api/demo';

const { createMessage } = useMessage();
const id = ref();

const siteOptions = ref<Recordable[]>([]);
const price = ref<number>();
const applyPrice = ref<number>();
const schemas: FormSchema[] = [
	{
		field: 'unitId',
		component: 'Select',
		label: '站点名称',
		required: true,
	},
	{
		field: 'cost',
		component: 'InputNumber',
		label: '费用',
		required: true,
		renderComponentContent: () => {
			return {
				addonAfter: () => '元',
			};
		},
		helpMessage: ['加氢站设备及安装费用（不含土建和土地成本）'],
		componentProps: () => {
			return {
				onblur: e => {
					if (e.target.value) {
						price.value = e.target.value;
						validate(['applySubsidyAmount']);
					}
				},
			};
		},
	},
	{
		field: 'applySubsidyAmount',
		component: 'InputNumber',
		label: '申请补贴金额',
		renderComponentContent: () => {
			return {
				addonAfter: () => '元',
			};
		},
		componentProps: () => {
			return {
				onblur: e => {
					if (e.target.value) {
						applyPrice.value = e.target.value;
					}
				},
			};
		},
		rules: [
			{
				required: true,
				validator: (_, value) => {
					if (price.value == undefined && value) {
						return Promise.reject('请先填写费用');
					}
					if (value > price.value! * 0.3) {
						return Promise.reject('补贴金额不超过费用的30%');
					}
					if (!value) {
						return Promise.reject('请输入申请补贴金额');
					}
					return Promise.resolve();
				},
				trigger: 'blur',
			},
		],
	},
	{
		field: 'purchaseContract',
		component: 'Upload',
		label: '采购合同',
		required: true,
		componentProps: ({ formModel }) => {
			return {
				title: '上传文件',
				type: 'default',
				explainText: '如是外文合同，需有中文译件',
				maxNumber: 1,
				api: uploadFile,
				onChange: e => {
					formModel.purchaseContract = e[0];
				},
				onPreview: e => {
					handlePreview(e);
				},
				onPreviewDownload: e => {
					handleDownloadByUrl(e);
				},
			};
		},
	},
	{
		field: 'primingAbility',
		component: 'Input',
		label: '计加注能力（公斤/日）',
		required: true,
		componentProps: {
			disabled: true,
		},
	},
	{
		field: 'is70mpa',
		component: 'Switch',
		label: '是否70Mpa',
		required: true,
		componentProps: {
			disabled: true,
			checkedChildren: '是',
			unCheckedChildren: '否',
			checkedValue: 1,
			unCheckedValue: 2,
		},
	},
	{
		field: 'divider-selects',
		component: 'Divider',
		label: '基础信息',
		helpMessage: ['如需修改请在基础信息中的企业信息修改'],
	},
	{
		field: 'companyName',
		component: 'Input',
		label: '企业名称',
		required: true,
		componentProps: {
			disabled: true,
		},
		colProps: {
			span: 12,
		},
		itemProps: {
			labelCol: { span: 8 },
			wrapperCol: { span: 14 },
		},
	},
	{
		field: 'address',
		component: 'Input',
		label: '地址',
		required: true,
		componentProps: {
			disabled: true,
		},
		colProps: {
			span: 12,
		},
		itemProps: {
			labelCol: { span: 5 },
			wrapperCol: { span: 14 },
		},
	},
	{
		field: 'contractPeople',
		component: 'Input',
		label: '联系人',
		required: true,
		componentProps: {
			disabled: true,
		},
		colProps: {
			span: 12,
		},
		itemProps: {
			labelCol: { span: 5 },
			wrapperCol: { span: 14 },
		},
	},
	{
		field: 'contractPhone',
		component: 'Input',
		label: '联系电话',
		required: true,
		componentProps: {
			disabled: true,
		},
		colProps: {
			span: 12,
		},
		itemProps: {
			labelCol: { span: 5 },
			wrapperCol: { span: 14 },
		},
	},
];
const [register, { validate, clearValidate, setFieldsValue, setProps, updateSchema }] = useForm({
	labelCol: {
		span: 8,
	},
	wrapperCol: {
		span: 8,
	},
	schemas,
	actionColOptions: {
		offset: 8,
		span: 6,
	},
	showResetButton: false,
	submitButtonOptions: {
		text: '提交',
		block: true,
	},
	submitFunc: customSubmitFunc,
});

function getCompanyInfo() {
	return new Promise<Recordable>(resolve => {
		resolve({
			id: 961501590126592,
			companyName: '嘉氢一（上海）能源科技有限公司',
			depositBank: '杭州银行股份有限公司上海杨浦支行',
			accountNumber: '3101040160000961869',
			taxpayerIdentificationNumber: '91310114MA1GUD491Y',
			address: '上海市嘉定区靖远路1555号1幢1层1002-03室',
			contractPeople: '吴涯',
			contractPhone: '18915672627',
			creatorId: '2c9dab998417303101842c8c6a8f121f',
			createTime: null,
			firstSendDate: '1900-01-20',
		});
	});
}

function getAllSite() {
	return new Promise<Recordable[]>(resolve => {
		resolve([
			{
				id: 961501585162240,
				name: '上海江桥加氢站',
				primingAbility: null,
				is70mpa: 2,
				createTime: null,
				companyId: '43e0c5e2ce094edf892d5e55af03cf8f',
				creatorId: '2c9dab998417303101842c8c6a8f121f',
				regionName: null,
				businessLicenseUniformId: null,
				firstSendDate: '2022-09-13',
			},
		]);
	});
}

getCompanyInfo().then(res => {
	setFieldsValue(res);
	id.value = res.id;
	getSite();
});

let siteName = ref();
function getSite() {
	getAllSite().then(res => {
		siteOptions.value = res;
		updateSchema({
			field: 'unitId',
			componentProps: ({ formModel }) => {
				return {
					options: siteOptions.value,
					fieldNames: { label: 'name', key: 'id', value: 'id' },
					onChange: e => {
						if (e) {
							const obj = siteOptions.value.find(item => item.id === e) || {};
							formModel.primingAbility = obj.primingAbility;
							formModel.is70mpa = obj.is70mpa;
							siteName.value = obj.name;
							clearValidate(['primingAbility', 'is70mpa']);
						} else {
							formModel.primingAbility = '';
							formModel.is70mpa = 2;
							siteName.value = '';
						}
					},
				};
			},
		});
	});
}

function handlePreview(_url) {
	// docPreview(url);
}

function handleDownloadByUrl(record) {
	downloadByUrl({
		url: record.url,
		fileName: record.name,
	});
}

async function customSubmitFunc() {
	try {
		const values = await validate();
		setProps({
			submitButtonOptions: {
				loading: true,
			},
		});

		values.companyId = id.value;
		values.unitName = siteName.value;
		values.equipmentInstallationList = values.equipmentInstallationList[0];
		values.purchaseContract = values.purchaseContract[0];
		values.invoice = values.invoice[0];
		values.otherFile = values.otherFile && values.otherFile[0];
		// saveConstruction(values).then(() => {
		// 	setProps({
		// 		submitButtonOptions: {
		// 			loading: false,
		// 		},
		// 	});
		createMessage.success('提交成功！');
		// });
	} catch (error) {}
}
</script>

<style scoped lang="less">
:deep(.ant-row .ant-form-item-control-input-content .ant-input-number-group-wrapper) {
	width: 100%;
}
</style>
